#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include "../Util.hpp"

std::string GetQueryString(std::string& query_string, std::string& method)
{
    method = getenv("METHOD");
    std::cerr << "METHOD=" << method << std::endl;

    // 测试POST的时候，直接崩溃
    if(method == "GET")
    {
        query_string = getenv("QUERY_STRING");
        std::cerr << "QUERY_STRING=" << query_string << std::endl;
    }
    else if(method == "POST")
    {
        std::string content_length_env = getenv("CONTENT_LENGTH");
        int content_length = atoi(content_length_env.c_str());
        char ch = 'X';
        while(content_length-- )
        {
            ssize_t s = read(0,  &ch, 1); 
            if(s == 1) query_string.push_back(ch); 
        }
        std::cerr << "BODY_TEST=" << query_string << std::endl; 
    }

    return query_string; 
}

int main()
{
    std::string query_string;
    std::string method;
    // 获得query_string，切割query_string
    GetQueryString(query_string, method);

    std::string sub1;
    std::string sub2;
    Util::CutString(query_string, sub1, sub2, "&");

    std::string key1;
    std::string value1;
    Util::CutString(sub1, key1, value1, "=");
    std::string key2;
    std::string value2;
    Util::CutString(sub2, key2, value2, "=");

    // 切割完成将数据交给HttpServer
    std::cout << key1 << " : " << value1 << std::endl;
    std::cout << key2 << " : " << value2 << std::endl;
    // 实现简单的加减乘除
    std::cout << "<br>" << std::endl;
    std::cout << value1 << " + " << value2 << " = "  << atoi(value1.c_str()) + atoi(value2.c_str()) << std::endl;
    std::cout << "<br>" << std::endl;
    std::cout << value1 << " - " << value2 << " = "  << atoi(value1.c_str()) - atoi(value2.c_str()) << std::endl;
    std::cout << "<br>" << std::endl;
    std::cout << value1 << " * " << value2 << " = "  << atoi(value1.c_str()) * atoi(value2.c_str()) << std::endl;
    std::cout << "<br>" << std::endl;
    std::cout << value1 << " / " << value2 << " = "  << atoi(value1.c_str()) / atoi(value2.c_str()) << std::endl;
    std::cout << "<br>" << std::endl;
    //write(1, key1.c_str(), key1.size()); 
    //write(1, value1.c_str(), value1.size());
    //write(1, key2.c_str(), key2.size()); 
    //write(1, value2.c_str(), value2.size());

    std::cerr << key1 << " : " << value1 << std::endl;
    std::cerr << key2 << " : " << value2 << std::endl;
    return 0;
}
